package aliyun_slb

import (
	"gitee.com/enlangs/goautocert/internal/models"
	"gitee.com/enlangs/goautocert/internal/modules/logger"
	"gitee.com/enlangs/goautocert/internal/modules/utils"
	"gitee.com/enlangs/goautocert/internal/routers/base"
	"github.com/go-macaron/binding"
	"gopkg.in/macaron.v1"
	"strconv"
	"strings"
)

// Index AliyunSLB 列表
func Index(ctx *macaron.Context) string {
	slb := new(models.AliyunSLB)
	queryParams := parseQueryParams(ctx)
	total, err := slb.Total(queryParams)
	if err != nil {
		logger.Error(err)
	}
	hosts, err := slb.List(queryParams)
	if err != nil {
		logger.Error(err)
	}

	jsonResp := utils.JsonResponse{}

	return jsonResp.Success(utils.SuccessContent, map[string]interface{}{
		"total": total,
		"data":  hosts,
	})
}

// All 获取所有 AliyunSLB
func All(ctx *macaron.Context) string {
	slb := new(models.AliyunSLB)
	slb.PageSize = -1
	hosts, err := slb.List(models.CommonMap{})
	if err != nil {
		logger.Error(err)
	}

	jsonResp := utils.JsonResponse{}

	return jsonResp.Success(utils.SuccessContent, hosts)
}

// Detail AliyunSLB详情
func Detail(ctx *macaron.Context) string {
	slb := new(models.AliyunSLB)
	id := ctx.ParamsInt(":id")
	err := slb.Find(id)
	jsonResp := utils.JsonResponse{}
	if err != nil || slb.Id == 0 {
		logger.Errorf("获取AliyunSLB详情失败#AliyunSLBid-%d", id)
		return jsonResp.Success(utils.SuccessContent, nil)
	}

	return jsonResp.Success(utils.SuccessContent, slb)
}

type AliyunSLBForm struct {
	Id                int
	RegionId          string `binding:"Required;MaxSize(64)"`
	LoadBalancerId    string `binding:"Required;MaxSize(64)"`
	ListenerPort      int
	BackendServerPort int
	Remark            string
}

// Error 表单验证错误处理
func (f AliyunSLBForm) Error(ctx *macaron.Context, errs binding.Errors) {
	if len(errs) == 0 {
		return
	}
	json := utils.JsonResponse{}
	content := json.CommonFailure("表单验证失败, 请检测输入")
	_, _ = ctx.Write([]byte(content))
}

// Store 保存、修改AliyunSLB信息
func Store(ctx *macaron.Context, form AliyunSLBForm) string {
	json := utils.JsonResponse{}
	slb := new(models.AliyunSLB)
	id := form.Id
	nameExist, err := slb.Exists(form.RegionId, form.LoadBalancerId, form.Id)
	if err != nil {
		return json.CommonFailure("操作失败", err)
	}
	if nameExist {
		return json.CommonFailure("AliyunSLB名已存在")
	}

	slb.RegionId = strings.TrimSpace(form.RegionId)
	slb.LoadBalancerId = strings.TrimSpace(form.LoadBalancerId)
	oldAliyunSLBModel := new(models.AliyunSLB)
	err = oldAliyunSLBModel.Find(int(id))
	if err != nil {
		return json.CommonFailure("AliyunSLB不存在")
	}

	if id > 0 {
		_, err = slb.UpdateBean(id)
	} else {
		id, err = slb.Create()
	}
	if err != nil {
		return json.CommonFailure("保存失败", err)
	}

	return json.Success("保存成功", nil)
}

// Remove 删除AliyunSLB
func Remove(ctx *macaron.Context) string {
	id, err := strconv.Atoi(ctx.Params(":id"))
	json := utils.JsonResponse{}
	if err != nil {
		return json.CommonFailure("参数错误", err)
	}

	slb := new(models.AliyunSLB)
	err = slb.Find(int(id))
	if err != nil {
		return json.CommonFailure("AliyunSLB不存在")
	}

	_, err = slb.Delete(id)
	if err != nil {
		return json.CommonFailure("操作失败", err)
	}

	return json.Success("操作成功", nil)
}

// 解析查询参数
func parseQueryParams(ctx *macaron.Context) models.CommonMap {
	var params = models.CommonMap{}
	params["Id"] = ctx.QueryInt("id")
	params["Email"] = ctx.QueryTrim("email")
	base.ParsePageAndPageSize(ctx, params)

	return params
}
